#include "stdafx.h"
#include <iostream>
#include "pcap.h"
#include "ETHFram.h"
#include "PacketQueue.h"
#include "TCPSession.h"

pcap_t * PrepareNWLive()
{
	pcap_if_t *alldevs;
	pcap_if_t *d;
	char errbuf[PCAP_ERRBUF_SIZE];
	u_int netmask;
	int inum;
	pcap_t *adhandle;
	char packet_filter[] = "tcp and not port 443";
	struct bpf_program fcode;
	int i = 0;

	/* Retrieve the device list */
	if (pcap_findalldevs(&alldevs, errbuf) == -1)
	{
		fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf);
		return NULL;
	}

	/* Print the list */
	for (d = alldevs; d; d = d->next)
	{
		printf("%d. %s", ++i, d->name);
		if (d->description)
			printf(" (%s)\n", d->description);
		else
			printf(" (No description available)\n");
	}

	if (i == 0)
	{
		printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
		return NULL;
	}

	printf("Enter the interface number (1-%d):", i);
	scanf("%d", &inum);

	if (inum < 1 || inum > i)
	{
		printf("\nInterface number out of range.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return NULL;
	}

	/* Jump to the selected adapter */
	for (d = alldevs, i = 0; i < inum - 1;d = d->next, i++);

	/* Open the adapter */
	if ((adhandle = pcap_open_live(d->name,	// name of the device
		65536,			// portion of the packet to capture. 
						// 65536 grants that the whole packet will be captured on all the MACs.
		1,				// promiscuous mode (nonzero means promiscuous)
		1000,			// read timeout
		errbuf			// error buffer
	)) == NULL)
	{
		fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return NULL;
	}

	/* Check the link layer. We support only Ethernet for simplicity. */
	if (pcap_datalink(adhandle) != DLT_EN10MB)
	{
		fprintf(stderr, "\nThis program works only on Ethernet networks.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return NULL;
	}

	if (d->addresses != NULL)
		/* Retrieve the mask of the first address of the interface */
		netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
	else
		/* If the interface is without addresses we suppose to be in a C class network */
		netmask = 0xffffff;

	//compile the filter
	if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) < 0)
	{
		fprintf(stderr, "\nUnable to compile the packet filter. Check the syntax.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return NULL;
	}

	//set the filter
	if (pcap_setfilter(adhandle, &fcode) < 0)
	{
		fprintf(stderr, "\nError setting the filter.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return NULL;
	}
	printf("\nlistening on %s...\n", d->description);

	/* At this point, we don't need any more the device list. Free it */
	pcap_freealldevs(alldevs);

	return adhandle;
}

pcap_t * PrepareCaptureFile(const char*fileName)
{
	pcap_t *fp;
	char errbuf[PCAP_ERRBUF_SIZE];

	if ((fp = pcap_open_offline(fileName,			// name of the device
		errbuf					// error buffer
	)) == NULL)
	{
		fprintf(stderr, "\nUnable to open the file %s.\n", fileName);
		return NULL;
	}
	printf("Open dump file:%s\n", fileName);
	return fp;
}


int main(int argc, char*argv[])
{
	pcap_t *adhandle;
	int res;
	struct pcap_pkthdr *header;
	const u_char *pkt_data;

	//struct tm *ltime;
	//char timestr[16];
	//time_t local_tv_sec;

	system("mkdir Download");
	CTCPSessionMgr::Initial();
#define QUENENUM	1
	CPacketQueue*nQueues[QUENENUM] = { 0 };
	for (int i = 0; i < QUENENUM; i++) {
		nQueues[i] = new CPacketQueue();
		if (nQueues[i]->Initial() == FALSE) {
			return -1;
		}
	}

#if DEBUGFILE
	if (argc != 2) {
		printf("usage: %s filename", argv[0]);
		return -1;
	}
	adhandle = PrepareCaptureFile(argv[1]);
#else
	if (CETHFram::Initialize() == false) {
		printf("Error: CETHFram::Initialize()\n");
		return -1;
	}

	adhandle = PrepareNWLive();
#endif
	if (!adhandle) {
		return -1;
	}
	/* Retrieve the packets */
	while ((res = pcap_next_ex(adhandle, &header, &pkt_data)) >= 0) {

		if (res == 0)
			/* Timeout elapsed */
			continue;

		/* convert the timestamp to readable format */
		//local_tv_sec = header->ts.tv_sec;
		//ltime = localtime(&local_tv_sec);
		//strftime(timestr, sizeof timestr, "%H:%M:%S", ltime);

		CETHFram *pkt = new CETHFram(pkt_data, header->len);
		if (!pkt)
			continue;

		int index = pkt->GetHashVal(QUENENUM);

		if (index < 0 || index >= QUENENUM) {
			delete pkt;
			continue;
		}

		nQueues[index]->AddPacket(pkt);
	}

	if (res == -1) {
		printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
		return -1;
	}

	pcap_close(adhandle);
	getchar();
	return 0;
}